<?php

namespace app\extensions\api;

use app\model\Package;
use Google\Cloud\BigQuery\ValueInterface;
use Google\Cloud\Core\ServiceBuilder;
use OSS\Core\OssException;
use OSS\Core\OssUtil;
use OSS\OssClient;
use support\Log;
use support\Redis;

class BigQuery
{


    public static function getFireBaseMessaging($package_id, $where = [], $result_type = ['list', 'total'],$page=1,$limit=1000)
    {
        $configuration = Package::getPackagePushConfig($package_id);
        $project_id = $configuration['project_id'];
        $datasetId = 'firebase_messaging';
        $tableId = 'data';
        $ptable = "{$project_id}.{$datasetId}.{$tableId}";
        //非服务service化的自定义组件
        $cloud = new ServiceBuilder([
            'projectId' => $project_id,
            'keyFile' => $configuration
        ]);
        $bigQueryClient = $cloud->bigQuery();

        $field = [
            'event_timestamp time',
            'message_id',
            'message_type',
            'sdk_platform',
            'event',
            'app_name',
            'analytics_label',
        ];
        $inField = ['message_id'];
        $fieldStr = implode(',', $field);
        $whereStr = [];
        foreach ($where as $field => $value) {
            if(in_array($field,$inField)){
                $valueStr = implode("','",$value);
                $whereStr[] = "{$field} in ('{$valueStr}')";
            }else{
                $whereStr[] = "{$field} = '{$value}'";
            }
        }
        $whereStr = implode(' and ', $whereStr);
        $list = [];
        $offset = ($page - 1 ) * $limit;
        foreach ($result_type as $type) {
            $sql = '';
            if ($type == 'list') {
                $sql = "SELECT {$fieldStr} FROM `{$ptable}` where {$whereStr} LIMIT {$limit} OFFSET {$offset}";
                $list[$type] = [];
            }
            if ($type == 'total') {
                $sql = "SELECT count(*) total FROM `{$ptable}` where {$whereStr}";
                $list[$type] = 0;
            }
            if(!$sql) continue;

            $queryJobConfig = $bigQueryClient->query(
                $sql
            );
            try {
                $queryResults = $bigQueryClient->runQuery($queryJobConfig);
                Log::channel('fcm')->info("list:BigQuery:sql:" . $sql);
                foreach ($queryResults->rows() as $row) {
                    foreach ($row as $field => &$value) {
                        /* @var $value \Google\Cloud\BigQuery\Timestamp */
                        if (is_object($value) && $value instanceof ValueInterface) {
                            $value = $value->formatAsString();
                        }
                    }
                    if($type=='total'){
                        $list[$type] = $row['total'] ?? 0;
                    }else{
                        $list[$type][] = $row;
                    }

                }
            } catch (\Throwable $e) {
                Log::channel('fcm')->error("BigQuery::" . $e->getMessage());
            }

        }
        return $list;
    }
}